package com.yayawan.laomigame;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;

import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.FileUtils;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
;
import android.view.KeyEvent;
import android.view.View;

import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.lidroid.jxutils.HttpUtils;
import com.lidroid.jxutils.exception.HttpException;
import com.lidroid.jxutils.http.ResponseInfo;
import com.lidroid.jxutils.http.callback.RequestCallBack;

import com.jiafan.dy.R;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.yayawan.laomigame.callback.LaomiGameApi;
import com.yayawan.laomigame.callback.X5WebChromeClientNew;
import com.yayawan.laomigame.callback.X5WebChromeClientNew1;
import com.yayawan.laomigame.utils.AlbumNotifyHelper;
import com.yayawan.laomigame.utils.AndroidBug5497Workaround;
import com.yayawan.laomigame.utils.AndroidBug5497Workaround2;
import com.yayawan.sdk.other.UpdateProgress_dialog;
import com.yayawan.sdk.utils.CircleProgressView;
import com.yayawan.sdk.utils.ToastUtil;
import com.yayawan.utils.DeviceUtil;
import com.yayawan.utils.PermissionUtils;
import com.yayawan.utils.Yayalog;
import com.ycbjie.webviewlib.base.X5WebChromeClient;
import com.ycbjie.webviewlib.base.X5WebViewClient;
import com.ycbjie.webviewlib.client.JsX5WebViewClient;
import com.ycbjie.webviewlib.inter.InterWebListener;
import com.ycbjie.webviewlib.inter.VideoWebListener;
import com.ycbjie.webviewlib.utils.X5WebUtils;
import com.ycbjie.webviewlib.view.X5WebView;
import com.ycbjie.webviewlib.widget.WebProgress;

import org.jsoup.Jsoup;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.security.Permission;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



/**
 * <pre>
 *     @author yangchong
 *     blog  : https://github.com/yangchong211
 *     time  : 2019/9/17
 *     desc  : webView页面
 *     revise: 暂时先用假数据替代
 * </pre>
 */
public class WebViewActivity extends AppCompatActivity {

    private X5WebView mWebView;
    private WebProgress progress;
    private String url;

    private static Activity mActivity;
    String basefilepath= android.os.Environment.getExternalStorageDirectory().getPath();
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() ==
                KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (mWebView!=null){
                mWebView.loadUrl("javascript:LaomiGameCallBack.onKeyDownPre()");
            }
            return true;
        }else {
            return super.onKeyDown(keyCode, event);
        }

    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.destroy();
            //mWebView = null;
        }
        super.onDestroy();
    }



    @Override
    public void onResume() {
        super.onResume();
        if (mWebView != null) {
            mWebView.onResume();
        }

        Yayalog.loger("onResume");

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                String clipboard=getCopy(mActivity);
                if (!TextUtils.isEmpty(clipboard)){
                    Yayalog.loger(decodeHttpUrl(clipboard));
                    mUrlText.setText(decodeHttpUrl(clipboard));
                }
            }
        },500);

    }

    Handler handler=new Handler(){};

    public static String decodeHttpUrl(String url) {
        String decodeurl =url;
        System.err.println(url);
        if (url.contains("http")){
            int start = url.indexOf("http");
            int end = url.lastIndexOf("/");
            decodeurl =   url.substring(start, end);
        }

        return decodeurl;
    }
    //系统剪贴板-获取:
    public static String getCopy(Context context) {

            ClipboardManager clipboard = (ClipboardManager) context.getSystemService(context.CLIPBOARD_SERVICE);
            //无数据时直接返回
            if (!clipboard.hasPrimaryClip()) {
                return null;
            }

            //如果是文本信息
            if (clipboard.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                ClipData cdText = clipboard.getPrimaryClip();
                ClipData.Item item = cdText.getItemAt(0);
                //此处是TEXT文本信息
                if (item.getText() != null && !item.getText().toString().equals("")) {
                   return item.getText().toString();


                }
            }
            return  null;


    }
    @Override
    protected void onStop() {
        super.onStop();
        if (mWebView != null) {
            mWebView.getSettings().setJavaScriptEnabled(false);
        }
    }
    LaomiGameApi mlaomigameapi;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        mActivity=this;

    Yayalog.loger(basefilepath);

        getOaid();
        initData();
        initView();
        initLogic();
        initPermission();
        //获取oaid保存在appcation中

        //mWebView.callHandler();

    }

    private void initPermission() {
        PermissionUtils.requestMorePermissions(this, new String[]{
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        },100);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        // TODO Auto-generated method stub
        super.onWindowFocusChanged(hasFocus);
       // hideBottomUIMenu();
    }
    public void initData() {
        Intent intent = getIntent();
        if (intent!=null){
            url = intent.getStringExtra("url");
        }
    }

    Button mShowVButton;
    Button mGetVButton;
    EditText mUrlText;
    Button mGethtmlcontent;
    public void initView() {


        mShowVButton = findViewById(R.id.et_d_showbutton);

        mGetVButton = findViewById(R.id.et_d_getbutton);
        mGethtmlcontent = findViewById(R.id.et_d_gethtmlcontent);
        mUrlText = findViewById(R.id.et_d_url);
        mUrlText.setText("https://v.douyin.com/J5cfosv/");



        mWebView = findViewById(R.id.web_view);

        mlaomigameapi=  new LaomiGameApi(mActivity,mWebView);
        progress = findViewById(R.id.progress);
        //progress.show();
      //  progress.setColor(this.getResources().getColor(R.color.colorAccent),this.getResources().getColor(R.color.colorPrimaryDark));

       // mWebView.loadUrl("http://api.hengxianggame.net/wan/index/?appid=2159465564");
       // mWebView.loadUrl("http://tl.3469.net:7903/");
       String appid= DeviceUtil.getGameInfo(mActivity,"qianguo_app_id").replace("kk","");
       String url="https://gm.kingoo.com.cn/"+"?kk="+System.currentTimeMillis()+"#/?app_id="+appid;
       Log.d("jiafan",url);
       //mWebView.loadUrl("https://gm.kingoo.com.cn/"+"?kk="+System.currentTimeMillis()+"#/?app_id="+appid);

      //  mWebView.loadUrl("https://v.douyin.com/J5cfosv");
        //file:///android_asset
        //mWebView.loadUrl("file:///android_asset/game/index.html");
        mWebView.setHorizontalScrollBarEnabled(false);//水平不显示
        mWebView.setVerticalScrollBarEnabled(false);//垂直不显示
        //Log.d()
        //mlaomigameapi
        // 设置与Js交互的权限
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        // 设置允许JS弹窗
       // mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.addJavascriptInterface(mlaomigameapi, "LaomiGameApi");//AndroidtoJS类对象映射到js的test对象

        //mWebView.loadUrl("file:///android_asset/test2.html");

        mWebView.getX5WebChromeClient().setWebListener(interWebListener);
        mWebView.getX5WebViewClient().setWebListener(interWebListener);
        mWebView.getX5WebChromeClient().setShowCustomVideo(false);
        mWebView.getX5WebChromeClient().hideCustomView();
        mWebView.getX5WebChromeClient().setVideoWebListener(new VideoWebListener() {
            @Override
            public void showVideoFullView() {

            }

            @Override
            public void hindVideoFullView() {

            }

            @Override
            public void showWebView() {

            }

            @Override
            public void hindWebView() {

            }
        });
        //兼容视频
        try {
            if (mWebView.getX5WebViewExtension() != null) {
                Bundle data = new Bundle();

                data.putBoolean("standardFullScreen", false);
                //true表示标准全屏，false表示X5全屏；不设置默认false，

                data.putBoolean("supportLiteWnd", false);
                //false：关闭小窗；true：开启小窗；不设置默认true，

                data.putInt("DefaultVideoScreen", 1);
                //1：以页面内开始播放，2：以全屏开始播放；不设置默认：1

                mWebView.getX5WebViewExtension().invokeMiscMethod("setVideoParams", data);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        //setShowCustomVideo
        mWebView.setInitialScale(1000);

       // KeyBoardListener.getInstance(this).init(mWebView);

//        X5WebChromeClientNew1 mx5WebChromeClientNew1 = new X5WebChromeClientNew1(mWebView, this);
//        mWebView.setWebChromeClient(mx5WebChromeClientNew1);
        // allowFileAccessFromFileURLs
// 本地 html
       new AndroidBug5497Workaround2(this,mWebView);

     //  hideBottomUIMenu();

    }



    private void initLogic() {

        mShowVButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showVideo();
            }
        });
        mGethtmlcontent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.loadUrl("javascript:window.local_obj.showSource(''+" +"document.getElementsByTagName('video')[0].getAttribute('src')+'');");

            }
        });
        mGethtmlcontent.setVisibility(View.GONE);
        mGetVButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {


                     Yayalog.loger("videourl  wei kong 重新加载");
                      mWebView.loadUrl("javascript:window.local_obj.showGetDownLoadUrlAndDownload(''+" +"document.getElementsByTagName('video')[0].getAttribute('src')+'');");


                   // Yayalog.loger(html);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        });
    }

    static  String nowVURL="";

    static  String nowDownloadVURL="";
    @SuppressLint("JavascriptInterface")
    private void showVideo() {
        // 1 get url text
         nowVURL = mUrlText.getText().toString().trim();

        //2 set webview client to get really video url
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");

        //  webview set ua
        String ua = mWebView.getSettings().getUserAgentString();//原来获取的UA
        mWebView.getSettings().setUserAgentString(ua.replace("Android","User-Agent:Mozilla/5.0(WindowsNT6.1;rv:2.0.1)Gecko/20100101Firefox/4.0.1"));

        //webview set viewclient
        mWebView.setWebViewClient(new MyWebViewC(mWebView,this));

        //3 put url in to webview show
        mWebView.loadUrl(nowVURL);
        mGetVButton.setText("点击下载");

    }



    final class InJavaScriptLocalObj {


        @JavascriptInterface
        public void showSource(String html) {
            //Log.d("HTML", html);
            Yayalog.loger(html);
//            //String kk="[a-zA-z]+://[^\"]*";
//            String kk="http(s)?://\\w{3,}(\\.\\w+)+(\\.\\w{2,3})";//正则表达式格式
//            Pattern patternCompile = Pattern.compile(kk);
//
//            //3.匹配后封装成Matcher对象
//            Matcher m = patternCompile.matcher(html);
//
//            //4.①利用Matcher中的group方法获取匹配的特定字符串 ②利用String的replace方法替换特定字符,得到抖音的去水印链接
//            String matchUrl ="";
//            m.find();
//            matchUrl=m.group(0);
//            Yayalog.loger("匹配到的值=="+matchUrl);
//
//            matchUrl =matchUrl.replaceAll("playwm", "play");

                Yayalog.loger("替换后的值=="+html);
                //if (html.contains("snssdk.com")){
                    nowDownloadVURL=html;
             //   }


        }


        @JavascriptInterface
        public void showGetDownLoadUrlAndDownload(String html) {
            //Log.d("HTML", html);
            Yayalog.loger(html);


            Yayalog.loger("替换后的值=="+html);
            //if (html.contains("snssdk.com")){
            nowDownloadVURL=html;
            //   }

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        getVideoSave2(nowDownloadVURL);
                    } catch (IOException e) {
                        Yayalog.loger("下载视频文件出错"+e.toString());
                        e.printStackTrace();
                    }
                }
            }).start();
        }


        @JavascriptInterface
        public void showSourceanddownload(String html) {
            //Log.d("HTML", html);
            Yayalog.loger(html);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            getVideoSave2(nowDownloadVURL);
                        } catch (IOException e) {
                            Yayalog.loger("下载视频文件出错"+e.toString());
                            e.printStackTrace();
                        }
                    }
                }).start();
            }





    }



    X5WebChromeClientNew mx5WebChromeClientNew;

    private InterWebListener interWebListener = new InterWebListener() {
        @Override
        public void hindProgressBar() {
         //   progress.hide();
        }

        @Override
        public void showErrorView(@X5WebUtils.ErrorType int type) {
            switch (type){
                //没有网络
                case X5WebUtils.ErrorMode.NO_NET:
                    break;
                //404，网页无法打开
                case X5WebUtils.ErrorMode.STATE_404:

                    break;
                //onReceivedError，请求网络出现error
                case X5WebUtils.ErrorMode.RECEIVED_ERROR:

                    break;
                //在加载资源时通知主机应用程序发生SSL错误
                case X5WebUtils.ErrorMode.SSL_ERROR:

                    break;
                default:
                    break;
            }
        }

        @Override
        public void startProgress(int newProgress) {
           // progress.setWebProgress(newProgress);
        }

        @Override
        public void showTitle(String title) {

        }


    };








    private static MiitHelper miitHelper;

    public static void getOaid() {
        // Inflate the menu; this adds items to the action bar if it is present.

        try {

            if (android.os.Build.VERSION.SDK_INT >= 28) {

                miitHelper = new MiitHelper(new MiitHelper.AppIdsUpdater() {

                    @Override
                    public void OnIdsAvalid(final String ids) {
                        // TODO Auto-generated method stub
                        App.oaid = ids;
                      //  Toast.makeText(mActivity, "Handle.active_handler======================"+ids, Toast.LENGTH_SHORT).show();


                    }
                });

                miitHelper.getDeviceIds(mActivity);

            }

        } catch (Exception e) {
            // TODO: handle exception
            Yayalog.loger("当前sdk 获取oaid id 异常：");
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        Uri result = (data == null || resultCode != RESULT_OK) ? null : data.getData();

        Yayalog.loger("uri ==== Path : "+result.getPath()
                +" getScheme : " +result.getScheme()
                +" Authority : " +result.getAuthority()
                +" Path: "+result.getPath()
                +" Port: "+result.getPort());
        if (requestCode == X5WebChromeClient.FILE_CHOOSER_RESULT_CODE) {

            mWebView.getX5WebChromeClient().uploadMessage(data, resultCode);
        } else if (requestCode == X5WebChromeClient.FILE_CHOOSER_RESULT_CODE_5) {
            Yayalog.loger(" X5WebChromeClient.FILE_CHOOSER_RESULT_CODE_5() uri path :"+result.getPath());
            mWebView.getX5WebChromeClient().uploadMessageForAndroid5(data, resultCode);
        }

        //这个是处理回调逻辑
      //  mWebView.getX5WebChromeClient().uploadMessageForAndroid5(data,requestCode);




    }



    class MyWebViewC extends JsX5WebViewClient {


        /**
         * 构造方法
         *
         * @param webView 需要传进来webview
         * @param context 上下文
         */
        public MyWebViewC(X5WebView webView, Context context) {
            super(webView, context);
        }

        @Override
        public void onPageFinished(WebView view, String url) {


            Yayalog.loger("ye mian jia zaiwanbi");
            mWebView.loadUrl("javascript:window.local_obj.showSource(''+" +"document.getElementsByTagName('video')[0].getAttribute('src')+'');");
            super.onPageFinished(view, url);
        }
    }






    private void getVideoSave2(String videourlx) throws IOException {
        //●抖音链接(使用手机分享功能,复制链接)




        //4.①利用Matcher中的group方法获取匹配的特定字符串 ②利用String的replace方法替换特定字符,得到抖音的去水印链接
        String kmatchUrl =videourlx;
        Yayalog.loger("开始下载vedio文件："+kmatchUrl);
        //System.out.println(matchUrl);


        Long timetmp = new Date().getTime();
        String fileAddress = basefilepath+"/抖音视频/douyin_"+timetmp+".mp4";
        Yayalog.loger("下载保存的路径 = "+fileAddress);
        //7.封装一个保存文件的路径对象
        File fileSavePath = new File(fileAddress);

        //注:如果保存文件夹不存在,那么则创建该文件夹
        File fileParent = fileSavePath.getParentFile();
        if(!fileParent.exists()){
            fileParent.mkdirs();
        }

        HttpUtils httpUtils = new HttpUtils();
        Yayalog.loger("下载dizhi url = "+kmatchUrl+fileAddress);
        httpUtils.download(kmatchUrl, fileAddress, new RequestCallBack<File>() {

            UpdateProgress_dialog updateProgress_dialog;
            long tempcurrent = 0;

            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
                // TODO Auto-generated method stub
                Yayalog.loger("下载成功");
              //  updateProgress_dialog.dialogDismiss();
                String fileName = fileAddress;
                Uri uri = Uri.fromFile(new File(fileName));
                //sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, uri));
                Toast.makeText(mActivity,"save in sd ka",Toast.LENGTH_LONG).show();
                scanFile(new File(fileName));
               // installProcess(mActivity,new File(fileName));
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mGetVButton.setText("下载成功" );
                    }
                });
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                // TODO Auto-generated method stub
                Yayalog.loger("下载失败" + msg);
                ToastUtil.showError(mActivity, "下载失败,请检查网络"+msg);
               // updateProgress_dialog.dialogDismiss();
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mGetVButton.setText("下载失败,点击重新下载" );
                    }
                });
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                // TODO Auto-generated method stub
                super.onLoading(total, current, isUploading);
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mGetVButton.setText("下载中：当前进度" +((current*100)/total)+"%");
                    }
                });

            }

            @Override
            public void onStart() {
                // TODO Auto-generated method stub
                super.onStart();

            }


        });
    }
//保存图片

    public  void scanFile(File file){
        String mimeType = getMimeType(file);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
            String fileName = file.getName();
            ContentValues values = new ContentValues();
            values.put(MediaStore.Video.Media.DISPLAY_NAME,fileName);
            values.put(MediaStore.Video.Media.MIME_TYPE, mimeType);
            values.put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_MOVIES);
            ContentResolver contentResolver = mActivity.getContentResolver();
            Uri uri = contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
            if(uri == null){
                // ToastUtils.showShort("图片保存失败");
                Yayalog.loger("scanFile 图片保存失败");
                return;
            }
            try {
                OutputStream out = contentResolver.openOutputStream(uri);
                FileInputStream fis = new FileInputStream(file);
                FileUtils.copy(fis,out);
                fis.close();
                out.close();
                // ToastUtils.showShort("图片保存成功");
                Yayalog.loger("scanFile 图片保存成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
//            MediaScannerConnection.scanFile(mActivity, new String[]{file.getPath()}, new String[]{mimeType}, (path, uri) -> {
//                //ToastUtils.showShort("图片已成功保存到" + path);
//                Yayalog.loger("图片已成功保存到" + path);
//            });

            try {
                MediaStore.Images.Media.insertImage(mActivity.getContentResolver(), file.getAbsolutePath(), file.getName(), null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 最后通知图库更新
            Uri contentUri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                contentUri = FileProvider.getUriForFile(mActivity, mActivity.getPackageName()+":yyw", file);
            } else {
                contentUri = Uri.parse("file://" + file.getAbsolutePath());
            }
            mActivity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, contentUri));
        }
    }


    public static String getMimeType(File file){
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String type = fileNameMap.getContentTypeFor(file.getName());
        return type;
    }




}
